package com.iscreen.core.utils.ejb;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;

import com.iscreen.utils.exceptions.IScreenException;
import com.iscreen.utils.exceptions.IScreenExceptionCodes;

public class ServiceLocator
{
	private static ServiceLocator instance = new ServiceLocator();

	private final static String JNDI_ENTITY_MANAGER = "iScreen/EntityManager";
	
	public static ServiceLocator getInstance()
	{
		return instance;
	}

	private ServiceLocator()
	{
	}

	public <T> T getEJB(Class<T> beanInterface) throws IScreenException
	{
		return getEJB(beanInterface.getSimpleName());
	}

	@SuppressWarnings("unchecked")
	private <T> T getEJB(String ejbName) throws IScreenException
	{
		try
		{
			InitialContext ctx = new InitialContext();
			Object obj = ctx.lookup(ejbName);
			return (T) obj;
		}
		catch (NamingException e)
		{
			throw new IScreenException(IScreenExceptionCodes.JNDI_ERROR, e);
		}
		
	}
	
	public EntityManager getEntityManager() throws IScreenException
	{
		try
		{
			InitialContext ctx = new InitialContext();
			Object obj = ctx.lookup(JNDI_ENTITY_MANAGER);
			return (EntityManager) obj;
		}
		catch (NamingException e)
		{
			throw new IScreenException(IScreenExceptionCodes.JNDI_ERROR, e);
		}
		
	}
	
}
